package com.ideaaedi.shardingjointable.config.sharding;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


/**
 * shardingsphere rules sharding 配置
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.0.0
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "spring.shardingsphere.rules.sharding")
public class RulesShardingProperties {

    private List<String> bindingTables;

    private Map<String, Set<String>> tableAndBindingTableMap = new ConcurrentHashMap<>(16);

    @PostConstruct
    private void parseBindingTables () {
        if (CollectionUtils.isEmpty(bindingTables)) {
            log.info("bindingTables is empty. skip.");
            return;
        }
        for (String bindingTable : bindingTables) {
            Set<String> tableSet = Arrays.stream(bindingTable.split(","))
                    .filter(StringUtils::isNotBlank)
                    .map(String::trim).collect(Collectors.toSet());
            if (CollectionUtils.isEmpty(tableSet)) {
                continue;
            }
            for (String logicTable : tableSet) {
                Set<String> bindingTableSet = tableAndBindingTableMap.get(logicTable);
                if (bindingTableSet == null) {
                    bindingTableSet = new HashSet<>();
                }
                bindingTableSet.addAll(tableSet);
                tableAndBindingTableMap.put(logicTable, bindingTableSet);
            }
        }
        log.info("parseBindingTables completed. tableAndBindingTableMap -> {}", tableAndBindingTableMap);
    }
}
